package com.abcode.st.websocket;

import com.abcode.st.websocket.common.CurrencySocketTypeEnums;
import com.abcode.st.websocket.common.NetHandler;
import com.abcode.st.websocket.common.RequestMsg;
import com.abcode.st.websocket.common.ResponseMsg;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;

/**
 * 航班动态socket处理类
 *
 * @author qinzhitao
 * @date 2023/3/21 15:41
 */
@Controller
public class CurrencySocketHandler implements NetHandler {
    @Resource
    private CurrencySocketService currencySocketService;

    private final static Logger log = LoggerFactory.getLogger(CurrencySocketHandler.class);


    @Override
    public void onDisconnect(Session session){
            currencySocketService.unReg(session);
    }

    @Override
    public void onException(Session session, Throwable cause){

    }

    @Override
    public void createSession(Session session){
        try {
            currencySocketService.reg(session);
        } catch (Exception e) {
            log.error("createSession|创建连接失败|sessionId:{}|",session.getId(),e);
        }
    }

    @Override
    public void onMessage(String msg, Session session){

        RequestMsg requestMsg = JSONObject.parseObject(msg, RequestMsg.class);
        String type = requestMsg.getType();
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), type);
        CurrencySocketTypeEnums socketTypeEnums = CurrencySocketTypeEnums.getTypeEnums(type);
        if(socketTypeEnums==null){
            log.error("|onMessage|type:{}|未做业务处理", type);
            ResponseMsg responseMsg = ResponseMsg.error("请求类型错误", type, null);
            //发送初始化数据给当前连接
            this.sendMessage(responseMsg.toString(), session);
            return;
        }
        switch (socketTypeEnums){
            case PING:
                ping(session);
                break;
            case AUDIT:
                List<String> list = new ArrayList<>();
                list.add("test");
                ResponseMsg responseMsg = ResponseMsg.ok(socketTypeEnums.getValue(), list);
                //发送初始化数据给当前连接
                this.sendMessage(responseMsg.toString(), session);
                break;
            default:
                log.error("|onMessage|type:{}|未做业务处理",socketTypeEnums.getValue());
        }

    }

    /**
     * 发送消息给当前客户端
     */
    public void sendMessage(String message, Session toSession) {
        try {
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }

    /**
     * 心跳
     * @param session
     */
    public void ping( Session session){
        ResponseMsg responseMsg = ResponseMsg.ok(CurrencySocketTypeEnums.PING.getValue(), null);
        this.sendMessage(responseMsg.toString(), session);
    }
}
